/*
 * @Description: 档案类型与档案类型映射
 * @Author: Zzt
 * @Date: 2022-11-05 16:00:09
 * @LastEditTime: 2023-02-15 18:02:00
 */
import { delItemById } from '@/utils/list';
import { Button, Form, Modal } from 'antd';
import { useEffect, useMemo, useState } from 'react';
import { useMappingRelationContext } from '../../contexts/MappingRelationContext';
import { useMappingRouterTypeContext } from '../../contexts/MappingRouterTypeContext';
import BaseList from './BaseList';
import FieldMatch from './FieldMatch';

const AddMappingList = (props: any) => {
  const { visible, onClose } = props;

  const { classification } = useMappingRouterTypeContext();
  const { addTAT, selectFond, selectAT } = useMappingRelationContext();
  // 字段匹配数据
  const [template, setTemplate] = useState<any>([]);
  const [levelList, setLevelList] = useState([]);
  const [form] = Form.useForm();

  // 当前step
  useEffect(() => {
    if (!visible) {
      form.resetFields();
      setTemplate([]);
    }
  }, [visible]);

  useEffect(() => {
    if (JSON.stringify(selectAT) !== '{}') {
      console.log('selectAT', selectAT);

      setLevelList(delItemById(0, selectAT.levelList, 'level'));
    }
  }, [selectAT]);

  /**
   * @description: 关闭弹窗
   */
  const onCancel = () => {
    onClose();
  };

  const onFinish = (value: any) => {
    const baseParam = { classification, type: 1 };
    addTAT({
      ...value,
      sourceArchiveTypeId: selectAT.id,
      sourceFondsId: selectFond.id,
      templateMetadataMapRelations: template,
      ...baseParam
    }).then(onCancel);
  };

  return (
    <Modal
      title={`${selectAT?.atName || ''}与档案类型的映射关系`}
      visible={visible}
      width={700}
      maskClosable={false}
      destroyOnClose
      onCancel={onCancel}
      footer={[
        <Button key="close" onClick={onCancel}>
          关闭
        </Button>,
        <Button
          key="finish"
          type="primary"
          onClick={() => {
            form.submit();
          }}
        >
          完成
        </Button>
      ]}
    >
      <Form
        labelCol={{ span: 4 }}
        wrapperCol={{ span: 20 }}
        labelAlign="left"
        form={form}
        onFinish={onFinish}
      >
        <BaseList form={form} visible={visible} title={selectAT?.atName} />
        {useMemo(
          () => (
            <FieldMatch updateTemplate={setTemplate} tplData={template} levelList={levelList} />
          ),
          [levelList]
        )}
      </Form>
    </Modal>
  );
};
export default AddMappingList;
